﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using NetSurveillance.WebApp.DataServices;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Foundations;
using NetSurveillance.WebApp.Models;
using NetSurveillance.WebApp.Utilities;
using Resources;

namespace NetSurveillance.WebApp.Controllers
{
    public class AccountController : Controller
    {
        public DataProvider DataProvider { get; set; }

        public PersistentDataContainer DataContainer
        {
            get { return PersistentDataContainer.Current; }
        }
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            if (DataProvider == null) DataProvider = new DataProvider(PresetValues.DefaultConnection);
            base.Initialize(requestContext);
        }

        public ActionResult LogOn()
        {
            LoadLogOnViewData();
            return View();
        }

        private void LoadLogOnViewData()
        {
            var langDic = new Dictionary<string, string> { { "zh-CN", "简体中文" }, { "en-US", "English" } };
            ViewData["LangList"] = new SelectList(langDic, "Key", "Value");
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user;
                var serviceResult = DataProvider.UserService.ValidateAccount(model.UserName, model.Password, out user);
                if(user != null && string.IsNullOrEmpty(serviceResult.Message))
                {
                    var userPms = DataProvider.UserService.GetAcctPermission(user.Id);
                    user.UserPermission = userPms;
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    DataContainer.Add(PresetValues.SessionKeys.CurrentUser, user);
                    RouteData.Values["lang"] = model.Lang;
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", MessageResource.LogonUnSuccess);
            }

            LoadLogOnViewData();
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            DataContainer.Clear();
            return RedirectToAction("LogOn", "Account");
        }

        public ActionResult Register()
        {
            ViewBag.PasswordLength = 6;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                    {
                        UserName = model.UserName,
                        Password = model.Password,
                        Email = model.Email,
                        RealName = model.RealName,
                        Phone = model.Phone,
                        UserType = UserType.Normal
                    };
                var result = DataProvider.UserService.Save(user);
                if (result.ExecutedSuccess)
                    return RedirectToAction("Index", "Home");
                ModelState.AddModelError("", result.Message);
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var currentUser = DataContainer.Read<User>(PresetValues.SessionKeys.CurrentUser);
                if (currentUser != null)
                {
                    if (currentUser.Password == model.OldPassword)
                    {
                        currentUser.Password = model.NewPassword;
                        var sr = DataProvider.UserService.Save(currentUser);
                        if (sr.ExecutedSuccess)
                        {
                            TempData[PresetValues.TempDataKeys.ErrorMessage] = "密码修改成功，请使用新密码重新登录";
                            return RedirectToAction("LogOff");
                        }
                        ModelState.AddModelError("", "密码修改失败，请重新操作");
                    }
                    else
                    {
                        ModelState.AddModelError("", "当前密码不正确");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "当前未登录，无法修改密码");
                }
            }

            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }


        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult IsUserNameUsed(string userName, long? id)
        {
            var user = id.HasValue
                           ? DataProvider.UserService.GetAllModels(false,
                                                                   p =>
                                                                   p.Id != id.Value && p.UserName == userName)
                           : DataProvider.UserService.GetAllModels(false, p => p.UserName == userName);
            return !user.Any()
                       ? Json(true, JsonRequestBehavior.AllowGet)
                       : Json(string.Format("用户名:{0}已存在，请更换一个再试", userName),
                              JsonRequestBehavior.AllowGet);
        }
    }
}
